package zmiddleware

import (
	"net/http"
	"strings"

	"gitee.com/youkelike/ziam/zload"
	"github.com/gin-gonic/gin"
)

func Publish() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		if c.Writer.Status() != http.StatusOK {
			return
		}

		var resource string
		paths := strings.Split(c.Request.URL.Path, "/")
		if len(paths) > 2 {
			resource = paths[2]
		}
		method := c.Request.Method
		notify(method, resource)
	}
}

func notify(method string, resource string) {
	var command zload.NotificationCommand
	switch resource {
	case "policies":
		command = zload.NoticePolicyChanged
	case "secrets":
		command = zload.NoticeSecretChanged
	default:
	}

	switch method {
	case "POST", "PUT", "DELETE", "PATCH":
		zload.NotifySingleton.Notify(zload.RedisPubSubChannel, zload.Notification{Command: command})
	default:
	}
}
